package com.example.demo.controller;

import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.demo.common.R;
import com.example.demo.utils.FileUtils;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Api(tags="上传")
@Log4j2
@RequestMapping("upload")
@RestController
public class UploadController {
	@Autowired
    private FileUtils fileUtils;

    @GetMapping("index")
    public String index(){
        return fileUtils.getUploadPath();
    }

    @PostMapping("file")
    public R file(MultipartFile file, @RequestParam(defaultValue = "") String subPath){
    	String uploadPath = fileUtils.getUploadPath();
        String filePath = Paths.get(subPath, fileUtils.getFileNameByTime(file.getOriginalFilename())).toString();
        String savePath = Paths.get(uploadPath, filePath).toString();

        if(fileUtils.uploadFile(file, savePath)){
            Map<String, Object> data = new HashMap<>();
            data.put("name", fileUtils.getFileNameTrimExt(file.getOriginalFilename()));
            data.put("path", filePath);
        	return R.ok(data);
        }else {
        	return R.fail("上传失败");
        }
    }
    @PostMapping("files")
    public R files(List<MultipartFile> files) {
        String uploadPath = fileUtils.getUploadPath();

        List<Map<String, String>> list = new ArrayList<>();
        for(MultipartFile file:files) {
            String filePath = Paths.get("", fileUtils.getFileNameByTime(file.getOriginalFilename())).toString();
            String savePath = Paths.get(uploadPath, filePath).toString();
        	if(fileUtils.uploadFile(file, savePath)) {
            	Map<String, String> map = new HashMap<>();
                map.put("name", fileUtils.getFileNameTrimExt(file.getOriginalFilename()));
                map.put("path", filePath);
                list.add(map);
            }else {
                return R.fail("上传失败");
            }
        }

        return R.ok(list);
    }
}
